package com.kxf.androidtestdemo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.kxf.androidtestdemo.R;

import java.lang.ref.WeakReference;

public class HandleTest2Activity extends AppCompatActivity {

    private TextView tv;
    private int id = 0;
    private Handler handler = new Myhandle(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("HandleTest1Activity", "onCreate");
        setContentView(R.layout.activity_handle_test2);
        tv = findViewById(R.id.tv);
        Message msg = handler.obtainMessage();
        ++id;
        msg.arg1 = id;
        handler.sendMessageDelayed(msg, 2000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("HandleTest1Activity", "onPause");
        Message msg = handler.obtainMessage();
        ++id;
        msg.arg1 = id;
        handler.sendMessageDelayed(msg, 40000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("HandleTest1Activity", "onDestroy");
//        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 当垃圾回收确定不再有对对象的引用时，由垃圾回收器对对象调用。
     * 子类重写@code finalize方法以释放系统资源或执行其他清理。
     *
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        Log.e("HandleTest1Activity", "finalize");
    }

    private static class Myhandle extends Handler {
        private WeakReference<Context> reference;//弱引用
        public Myhandle(Context context) {
            reference = new WeakReference<>(context);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Context context = reference.get();
            Log.e("Myhandle", "handleMessage context=" + context);
            if (null != context){
                Toast.makeText(context, msg.arg1 + " handleMessage", Toast.LENGTH_LONG).show();
            }
        }
    }
}
